// 引入图表库
import * as echarts from '../../../cmpts/echarts/echarts';

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    // 图表类型
    chartType: {
      type: String,
      value: 'bar' // bar, line, pie, radar, scatter
    },
    // 图表标题
    title: {
      type: String,
      value: ''
    },
    // 图表数据
    chartData: {
      type: Object,
      value: {},
      observer: function(newVal) {
        if (newVal && Object.keys(newVal).length > 0) {
          this._renderChart();
        }
      }
    },
    // 自定义配置
    config: {
      type: Object,
      value: {}
    },
    // 图表高度
    height: {
      type: Number,
      value: 300
    },
    // 是否显示图例
    showLegend: {
      type: Boolean,
      value: true
    },
    // 是否显示标题
    showTitle: {
      type: Boolean,
      value: true
    },
    // 自动刷新间隔（毫秒），0表示不自动刷新
    refreshInterval: {
      type: Number,
      value: 0
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    ec: {
      lazyLoad: true
    },
    chart: null,
    timer: null
  },

  /**
   * 组件的生命周期
   */
  lifetimes: {
    attached: function() {
      // 在组件实例进入页面节点树时执行
    },
    ready: function() {
      // 在组件在视图层布局完成后执行
      this._initChart();
      
      // 设置自动刷新
      if (this.properties.refreshInterval > 0) {
        this.data.timer = setInterval(() => {
          this._refreshChart();
        }, this.properties.refreshInterval);
      }
    },
    detached: function() {
      // 在组件实例被从页面节点树移除时执行
      if (this.data.timer) {
        clearInterval(this.data.timer);
      }
      
      // 释放图表实例
      if (this.data.chart) {
        this.data.chart.dispose();
      }
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 初始化图表
    _initChart: function() {
      this.chartComponent = this.selectComponent('#chart');
      if (this.chartComponent) {
        this.chartComponent.init((canvas, width, height, dpr) => {
          const chart = echarts.init(canvas, null, {
            width: width,
            height: height,
            devicePixelRatio: dpr
          });
          
          this.setData({
            chart
          });
          
          // 初始渲染图表
          if (this.properties.chartData && Object.keys(this.properties.chartData).length > 0) {
            this._renderChart();
          }
          
          return chart;
        });
      }
    },
    
    // 渲染图表
    _renderChart: function() {
      if (!this.data.chart) return;
      
      const chartOptions = this._getChartOptions();
      this.data.chart.setOption(chartOptions);
    },
    
    // 刷新图表
    _refreshChart: function() {
      // 触发父组件更新数据
      this.triggerEvent('refresh');
      
      // 如果图表实例存在，则重新渲染
      if (this.data.chart) {
        this._renderChart();
      }
    },
    
    // 获取图表配置
    _getChartOptions: function() {
      const { chartType, title, chartData, showLegend, showTitle, config } = this.properties;
      
      // 基础配置
      const options = {
        title: showTitle ? {
          text: title,
          left: 'center'
        } : undefined,
        tooltip: {
          trigger: 'item'
        },
        legend: showLegend ? {
          orient: 'horizontal',
          bottom: 10
        } : undefined,
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          top: showTitle ? '15%' : '3%',
          containLabel: true
        }
      };
      
      // 根据图表类型配置
      switch (chartType) {
        case 'bar':
          this._configBarChart(options, chartData);
          break;
        case 'line':
          this._configLineChart(options, chartData);
          break;
        case 'pie':
          this._configPieChart(options, chartData);
          break;
        case 'radar':
          this._configRadarChart(options, chartData);
          break;
        case 'scatter':
          this._configScatterChart(options, chartData);
          break;
        default:
          this._configBarChart(options, chartData);
      }
      
      // 合并自定义配置
      return { ...options, ...config };
    },
    
    // 配置柱状图
    _configBarChart: function(options, chartData) {
      if (!chartData || !chartData.series || !chartData.xAxis) return options;
      
      options.xAxis = {
        type: 'category',
        data: chartData.xAxis,
        axisLabel: {
          interval: 0,
          rotate: chartData.xAxis.length > 5 ? 30 : 0
        }
      };
      
      options.yAxis = {
        type: 'value'
      };
      
      options.series = Array.isArray(chartData.series) ? 
        chartData.series.map(item => ({
          type: 'bar',
          name: item.name,
          data: item.data,
          itemStyle: item.itemStyle
        })) : 
        [{
          type: 'bar',
          name: chartData.name || '',
          data: chartData.series,
          itemStyle: chartData.itemStyle
        }];
      
      return options;
    },
    
    // 配置折线图
    _configLineChart: function(options, chartData) {
      if (!chartData || !chartData.series || !chartData.xAxis) return options;
      
      options.xAxis = {
        type: 'category',
        data: chartData.xAxis,
        boundaryGap: false
      };
      
      options.yAxis = {
        type: 'value'
      };
      
      options.series = Array.isArray(chartData.series) ? 
        chartData.series.map(item => ({
          type: 'line',
          name: item.name,
          data: item.data,
          smooth: true,
          areaStyle: item.areaStyle,
          lineStyle: item.lineStyle
        })) : 
        [{
          type: 'line',
          name: chartData.name || '',
          data: chartData.series,
          smooth: true,
          areaStyle: chartData.areaStyle,
          lineStyle: chartData.lineStyle
        }];
      
      return options;
    },
    
    // 配置饼图
    _configPieChart: function(options, chartData) {
      if (!chartData || !chartData.series) return options;
      
      // 饼图特殊处理
      options.tooltip.trigger = 'item';
      options.tooltip.formatter = '{a} <br/>{b} : {c} ({d}%)';
      
      options.series = [{
        type: 'pie',
        name: chartData.name || '',
        radius: chartData.radius || '55%',
        center: ['50%', '50%'],
        data: chartData.series.map(item => ({
          name: item.name,
          value: item.value
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }];
      
      return options;
    },
    
    // 配置雷达图
    _configRadarChart: function(options, chartData) {
      if (!chartData || !chartData.indicator || !chartData.series) return options;
      
      options.radar = {
        indicator: chartData.indicator
      };
      
      options.series = [{
        type: 'radar',
        name: chartData.name || '',
        data: chartData.series.map(item => ({
          name: item.name,
          value: item.value,
          areaStyle: item.areaStyle
        }))
      }];
      
      return options;
    },
    
    // 配置散点图
    _configScatterChart: function(options, chartData) {
      if (!chartData || !chartData.series) return options;
      
      options.xAxis = {
        type: 'value',
        name: chartData.xName || ''
      };
      
      options.yAxis = {
        type: 'value',
        name: chartData.yName || ''
      };
      
      options.series = Array.isArray(chartData.series) ? 
        chartData.series.map(item => ({
          type: 'scatter',
          name: item.name,
          data: item.data,
          symbolSize: function(data) {
            return item.symbolSize ? item.symbolSize(data) : 10;
          }
        })) : 
        [{
          type: 'scatter',
          name: chartData.name || '',
          data: chartData.series,
          symbolSize: function(data) {
            return chartData.symbolSize ? chartData.symbolSize(data) : 10;
          }
        }];
      
      return options;
    }
  }
}) 